package com.innovation.sys.common.singleton;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.innovation.sys.common.vo.SFTPItem;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class ChannelSftpSingleton {
	
	private static Logger logger = LoggerFactory.getLogger(ChannelSftpSingleton.class);
	
	private static ChannelSftpSingleton instance;
	private ChannelSftp channelSftp;
	private Session session;

	private ChannelSftpSingleton() {
	}

	public static ChannelSftpSingleton getInstance() {
		if (instance == null) {
			instance = new ChannelSftpSingleton();
		}
		return instance;
	}

	public ChannelSftp getChannelSftp() throws JSchException {
		if (channelSftp != null) {
			return channelSftp;
		}
		channelSftp = getChannel();
		return channelSftp;
	}

	public void closeChannel() throws Exception {
		if (channelSftp != null) {
			channelSftp.disconnect();
		}
		if (session != null) {
			session.disconnect();
		}
		logger.info("disconnecting SFTP successfully!");
	}

	private ChannelSftp getChannel() throws JSchException {
		SFTPItem sftpItem = new SFTPItem();
		JSch jsch = new JSch();
		session = jsch.getSession(sftpItem.getIdentity(), sftpItem.getHost(), Integer.parseInt(sftpItem.getPort()));
		session.setPassword(sftpItem.getPassword());
		Properties configTemp = new Properties();
		configTemp.put("StrictHostKeyChecking", "no");
		session.setConfig(configTemp);
		session.setTimeout(60000);
		session.connect();
		Channel channel = session.openChannel("sftp");
		// 建立SFTP通道的连接
		channel.connect();
		logger.info("SFTP connecting successfully！");
		return (ChannelSftp) channel;
	}

}
